package test

import (
	"bufio"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"os"
)

func Add(n int) int {
	sum := 0
	for i := 0; i < n; i++ {
		sum += i
	}
	return sum
}

type Monster struct {
	Name  string
	Age   int
	Skill string
}

const (
	FILENAME = "C:\\Users\\junma\\Desktop\\goland-workspace\\goland-study\\src\\go_code\\chapter12-test\\test.txt"
)

func (m Monster) Store() {
	//打开资源
	open, err := os.OpenFile(FILENAME, os.O_WRONLY|os.O_CREATE, 0)
	if err != nil {
		fmt.Println("打开文件失败,路径：", FILENAME)
	}
	//关闭资源
	defer func(open *os.File) {
		err = open.Close()
		//if err != nil {
		//	log.Fatalln("关闭资源失败！！！")
		//}
	}(open)
	//转换为json
	marshal, err := json.Marshal(Monster{
		Name:  "tom",
		Age:   12,
		Skill: "生活",
	})
	if err != nil {
		fmt.Println("json转换失败。。")
	}
	log.Println("json转换后", string(marshal))

	//获取写对象
	writer := bufio.NewWriter(open)

	//写文件
	w, err := writer.Write([]byte(marshal))
	if err != nil {
		fmt.Println("写文件失败")
	}
	fmt.Println("写之后的int数", w)

	err = writer.Flush()
	if err != nil {
		fmt.Println("刷新入文件")
	}
}

func (m Monster) ReStore() {
	//读文件
	file, _ := ioutil.ReadFile(FILENAME)
	json.Unmarshal(file, &m)
	fmt.Println(m)
}
